package com.kc.gb.device.configurations;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class ThreadPoolConfiguration {

    public static final String CommonExecutor = "KC-CommonPool";

    @Primary
    @Bean(ThreadPoolConfiguration.CommonExecutor)
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：线程池创建时候初始化的线程数
        executor.setCorePoolSize(20);
        // 最大线程数：线程池最大的线程数，只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(50);
        // 缓冲队列：用来缓冲执行任务的队列
        executor.setQueueCapacity(200);
        // 允许线程的空闲时间60秒：当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 线程池名的前缀：设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix(ThreadPoolConfiguration.CommonExecutor+"-");
        // 缓冲队列满了之后的拒绝策略：由调用线程处理（一般是主线程）
        //AbortPolicy：丢弃任务并抛出 RejectedExecutionException 异常
        //DiscardPolicy：丢弃任务，但是不抛出异常。可能导致无法发现系统的异常状态
        //DiscardOldestPolicy：丢弃队列最前面的任务，然后重新提交被拒绝的任务
        //CallerRunsPolicy：不丢弃任务 由调用线程处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭
        executor.setAllowCoreThreadTimeOut(true);
        //executor.setTaskDecorator(TtlRunnable::get);
        executor.setTaskDecorator(new TaskDecorator() {
            @Override
            public Runnable decorate(Runnable runnable) {
                return () -> {
                    try {
                        runnable.run();
                    } catch (Exception e) {
                        // 处理异常，例如记录日志
                        log.error("CommonPool task failed:{}", e.getMessage(),e);
                        // 重新抛出异常以便调用者知道发生了错误
                        throw e;
                    }
                };
            }
        });
        executor.initialize();
        return executor;
    }


    @Bean
    @ConditionalOnMissingBean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        // 线程池大小
        threadPoolTaskScheduler.setPoolSize(10);
        // 线程名称
        threadPoolTaskScheduler.setThreadNamePrefix("TaskSchedulerPool-");
        // 等待时长
        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        // 调度器shutdown被调用时等待当前被调度的任务完成
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskScheduler.initialize();
        return threadPoolTaskScheduler;
    }
}
